package com.tanhua.autoconfig.template;

import com.tanhua.autoconfig.properties.SmsProperties;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/*
*发送短信的核心类，通过SpringBoot的自动装配将SmsTemplate注入Ioc容器
* */
public class SmsTemplate {

        private SmsProperties properties;
        /*
        * 通过使用SmsTemplate的有参构造函数，将SmsProperties的对象
        * (内部有两个参数分别是APIID:,APIKEY)引入SmsTemplate类中，
        * 赋值给变量properties
        * */
        public SmsTemplate(SmsProperties properties){
            this.properties = properties;
        }
        /*
        * 发送短信的核心方法，使用互亿无线提供发送短信代码的案例进行改造，
        * 使用传入四个参数 moblie电话号码,moblie_code验证码，需要前端，和controller层传入
        *
        * APIID:,APIKEY:互亿无线的账号密码，为了后续可以更改这两个参数达到换账号密码的需求，
        *               我们将从yml配置文件获取中动态的获取这两个参数
        * */
        public void sendSms(String moblie ,String mobile_code){

            String Url = "http://106.ihuyi.com/webservice/sms.php?method=Submit";

            HttpClient client = new HttpClient();
            PostMethod method = new PostMethod(Url);

            client.getParams().setContentCharset("UTF-8");
            method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");

            String content = new String("您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。");

            NameValuePair[] data = {//提交短信
                    new NameValuePair("account",properties.getAPIID()),
                    new NameValuePair("password", properties.getAPIKEY()),
                    new NameValuePair("mobile", moblie),
                    new NameValuePair("content", content),
            };
            method.setRequestBody(data);
            try {
                client.executeMethod(method);
                String SubmitResult = method.getResponseBodyAsString();
                Document doc = DocumentHelper.parseText(SubmitResult);
                Element root = doc.getRootElement();
                String code = root.elementText("code");
                String msg = root.elementText("msg");
                String smsid = root.elementText("smsid");

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
}
